package com.czmini.cztest.common;

import com.alibaba.fastjson.JSONObject;
import com.czmini.cztest.dao.ZcTestJenkinsMapper;
import com.czmini.cztest.entity.ZcTestJenkins;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.client.JenkinsHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.util.Objects;

/**
 * @ProjectName: cztest
 * @Package: com.czmini.cztest.common
 * @ClassName: JenkinsFactory
 * @Author: 还是那个橙子
 * @Description:获取Jenkins 服务
 * @Date: 2022/5/1 23:43
 * @Version: 1.0
 */

@Slf4j
@Component
public class JenkinsFactory {

    @Autowired
    private ZcTestJenkinsMapper zcTestJenkinsMapper;

    /**
     * 获取Jenkins的java客户端的JenkinsServer
     * @param createUserId 创建者id
     * @param jenkinsId   jenkins id
     *
     * @return
     */
    public JenkinsServer getJenkinsServer(Integer createUserId, Integer jenkinsId){
        JenkinsServer jenkinsServer = new JenkinsServer(getJenkinsHttpClient(createUserId, jenkinsId));
        return jenkinsServer;
    }

    //获取Jenkins的java客户端的JenkinsHttpClient
    public JenkinsHttpClient getJenkinsHttpClient(Integer createUserId, Integer jenkinsId) {
        JenkinsHttpClient jenkinsHttpClient = null;
        try {
            ZcTestJenkins result = getZcTestJenkins(createUserId, jenkinsId);
            log.info("获取Jenkins的java客户端的JenkinsHttpClient" + JSONObject.toJSONString(result));

            jenkinsHttpClient = new JenkinsHttpClient(URI.create(result.getUrl()), result.getUserName(), result.getPassword());
        } catch (Exception e) {
            String tips = "获取jenkins服务异常" + e.getMessage();
            log.error("获取Jenkins的java客户端的JenkinsHttpClient失败", e.getMessage());
            throw new ServiceException(tips);
        }
        return jenkinsHttpClient;

    }

    //根据环境信息获取数据库中配置的Jenkins服务信息
    public ZcTestJenkins getZcTestJenkins(Integer createUserId, Integer jenkinsId) {
        ZcTestJenkins queryzcTestJenkins = new ZcTestJenkins();
        queryzcTestJenkins.setCreateUserId(createUserId);
        queryzcTestJenkins.setId(jenkinsId);
        ZcTestJenkins result = zcTestJenkinsMapper.selectOne(queryzcTestJenkins);

        if(Objects.isNull(result)){
            throw new ServiceException("未查到Jenkins信息");
        }
        return result;
    }
    //


}
